package services

import (
	"net"
	"github.com/beego/beego/v2/adapter/logs"
	"strings"
	"fmt"
)

type intfInfo struct {
	Name       string
	MacAddress string
	Ipv4       []string
}

func getNetworkInfo() ([]intfInfo, error) {
	intf, err := net.Interfaces()
	if err != nil {
		logs.Error("get network info failed: %v", err)
		return nil,err
	}
	var is = make([]intfInfo, len(intf))
	for i, v := range intf {
		ips, err := v.Addrs()
		if err != nil {
			logs.Error("get network addr failed: %v", err)
			return nil ,err
		}
		//此处过滤loopback（本地回环）和isatap（isatap隧道）
		if !strings.Contains(v.Name, "Loopback") && !strings.Contains(v.Name, "isatap") {
			is[i].Name = v.Name
			is[i].MacAddress = v.HardwareAddr.String()
			for _, ip := range ips {
				if strings.Contains(ip.String(), ".") {
					is[i].Ipv4 = append(is[i].Ipv4, ip.String())
				}
			}
		}

	}
	return is, nil
}

//返回MAC地址
func ShowHardwareCode() (string,error) {
	net,err := getNetworkInfo()
	if(err != nil) {
		logs.Error("获取硬件信息失败！")
		return "",err
	}
	for _,v := range net {
		fmt.Println(fmt.Sprintf("addr=%s,len=%d", v.MacAddress, len(v.MacAddress)))
	}
	return "",nil
}